function EditorReport(p){}
EditorReport.prototype.getBase64Image = function (img) {
	// Create an empty canvas element
	var canvas = document.createElement("canvas");
	canvas.width = img.width;
	canvas.height = img.height;
	// Copy the image contents to the canvas
	var ctx = canvas.getContext("2d");
	ctx.drawImage(img, 0, 0);
	// Get the data-URL formatted image
	// Firefox supports PNG and JPEG. You could check img.src to
	// guess the original format, but be aware the using "image/jpg"
	// will re-encode the image.
	var dataURL = canvas.toDataURL("image/png");
	//console.log(dataURL); //here is where I get 'data:,'
	//return dataURL.replace(/^data:image\/(png|jpg);base64,/, "");
	return dataURL;
}
EditorReport.prototype.setReportEvents=function(){
	$("#designboard .designpager div.tmpelement").draggable({
		stop: function(ev, ui){
			//$(this).text("Parou de arrastar");
			var eleM = $(this);
			propsElement.fillProps(eleM);
			//alert("posso setar quantas vezes ?");
		}
		,'containment': 'parent'
	}).click(function(){
		//alert(this.id);
		$("#designboard .designpager .elementSelecionado").removeClass("elementSelecionado");
		$(".treeview .band li").removeClass("selecionado");
		$("#tree_item_id_"+this.id).addClass("selecionado");
		var eleM = $(this);
		eleM.addClass("elementSelecionado");
		propsElement.fillProps(eleM);		
	});
	    //Make element droppable
    $("#designpagerele .designpagerband").droppable({
		accept: ".item",
        drop: function (ev, ui) {
			var elem = $(this);
			var itemEmDrop = $(ui.helper);
			var novoElemento = ui.draggable;
			var pos = elem.position();
			/*
			console.log($(this).attr("id"));
			console.log(pos.left)
			console.log(pos.top)
			*/
			var tmElents = elem.find(".tmpelement").length;
			var novoItem = {"type":"text","fontSize":14,"_top":0,"top":0,"left":0,"_left":0,"height":20,"width":150,"borderSize":0,"borderColor":"rgb(252,252,252)","fillColor":"rgb(252,252,252)","fontColor":"rgb(0,0,0)"};
			//novoItem["id"] = elem.attr("id")+tmElents;
			novoItem["text"] = "text";
			novoItem["band"] = elem.index();
			if(itemEmDrop.hasClass("item")){
				//novoItem["textExpression"] = "$F{"+itemEmDrop.text()+"}";
				novoItem["text"] = "$F{"+itemEmDrop.text()+"}";
				
				if(itemEmDrop.hasClass("variableitem")){
					novoItem["text"] = "$V{"+itemEmDrop.text()+"}";
				}
				
				novoItem["type"] = "textField";
				elem.append(editorR.addTextField(novoItem));
			}else{				
				elem.append(editorR.addText(novoItem));
			}
			editorR.setReportEvents();
			//var eleIndex = elem.index();
			
			//_jeport.bands[eleIndex].elements[tmElents] = novoItem;
			//editorR.addTreeViewItem(novoItem);
			//$("#b_"+elem.attr("id")).append();
			//var bandSelecionada = $("#designpagerele .bandselecionada");
			
			
			$("#b_"+ elem.attr("id")).append(editorR.addTreeViewItem(novoItem));
			editorR.setReportTreeViewEvents();
			//editorR.createTreeView(_jeport);
			//alert("recebi"+elem.hasClass(""));
        }
    }).click(function(){
		$("#designpagerele .bandselecionada").removeClass("bandselecionada");
		$(this).addClass("bandselecionada");
	}).filter(":first").addClass("bandselecionada");
}
EditorReport.prototype.setReportTreeViewEvents=function(){	
	$("#subconteudo .treeview ul span").click(function(){	
		var eleM = $(this);
		if(eleM.hasClass("expandid")){
			eleM.removeClass("expandid").parent().css({"height":"20px"});
		}else{
			eleM.addClass("expandid").parent().css({"height":"auto"});
		}			
		if(eleM.parent().hasClass("band")){
			propsElement.dtaSetValuesPropp.htmlX.hide();
			$("#designboard .designpager .elementSelecionado").removeClass("elementSelecionado");
			var tmpId = eleM.parent().attr("id").replace("b_","");
			var eleMM = $("#"+tmpId);
			eleMM.addClass("elementSelecionado");
			
			propsElement.fillProps(eleMM);
		}			
		if(eleM.hasClass("remove_item")){
			$("#"+eleM.parent().attr("id").replace("tree_item_id_","")).remove();
			eleM.parent().remove();
		}
	});
	$("#subconteudo .treeview ul.dataset").click(function(event){
		var str = "";
		propsElement.dtaSetValuesPropp.setValue(str);
		propsElement.idPropp.setValue(_jeport.dataSets[0]["dataSet"]);		
		propsElement.dtaSetValuesPropp.htmlX.show();	
	});
	$("#subconteudo .treeview ul.band li").click(function(event){
		$("#"+this.id.replace("tree_item_id_","")).click();
	});
		//$("#subconteudobtns .btn-group-vertical .btn").draggable({
	$("#subconteudo .treeview ul.dataset .item").draggable({
        helper: 'clone',
		cursor: "move",
	    start:function(event, ui){},
	    update: function(event, ui) {}
    });
}

EditorReport.prototype.setReport=function(dtareport){
	dtareport.bands["_top"]=[0,0,0,0,0];	
	this.addBand(dtareport,0);
	this.addBand(dtareport,1);
	this.addBand(dtareport,2);
	this.addBand(dtareport,3);
	this.addBand(dtareport,4);
	this.addElements(dtareport.visual_elements);
	this.addElements(dtareport.images);
	this.addElements(dtareport.texts);
	this.setReportEvents();
	return null;
};
EditorReport.prototype.addElement = function(props){
	if(!props.id){
		var tmelem = _jeport.texts.id.length;
		props.id = "te_"+props.band+"_"+tmelem;
		for(var chave in props){	
			_jeport.texts[chave][tmelem] = props[chave];
		}		
	}
	var propsCss = {"border":props.borderSize+"px solid "+props.borderColor,"backgroundColor":props.fillColor,"width":props.width,"height":props.height,"top":props.top,"left":props.left};
	return $('<div class="tmpelement">').css({"position":"absolute","z-index":15}).css(propsCss).attr("id","el_"+props.id);
};
EditorReport.prototype.addCircle = function(props){
	if(!props.id){
		var tmelem = _jeport.visual_elements.id.length;
		props.id = "ve_"+props.band+"_"+tmelem;
		for(var chave in props){	
			_jeport.visual_elements[chave][tmelem] = props[chave];
		}		
	}
	var propsCss = {"border":props.borderSize+"px solid "+props.borderColor,"backgroundColor":props.fillColor,"width":props.width,"height":props.height,"top":props.top,"left":props.left};
	return $('<div class="tmpelement">').css({"position":"absolute","z-index":10}).css(propsCss).attr("id","el_"+props.id);
};
EditorReport.prototype.addRect = function(props){
	if(!props.id){
		var tmelem = _jeport.visual_elements.id.length;
		props.id = "ve_"+props.band+"_"+tmelem;
		for(var chave in props){	
			_jeport.visual_elements[chave][tmelem] = props[chave];
		}		
	}
	var propsCss = {"border":props.borderSize+"px solid "+props.borderColor,"backgroundColor":props.fillColor,"width":props.width,"height":props.height,"top":props.top,"left":props.left};
	return $('<div class="tmpelement eleRect">').css({"position":"absolute","z-index":10}).css(propsCss).attr("id","el_"+props.id);
};
EditorReport.prototype.addTriangle = function(props){
	if(!props.id){
		var tmelem = _jeport.visual_elements.id.length;
		props.id = "ve_"+props.band+"_"+tmelem;
		for(var chave in props){	
			_jeport.visual_elements[chave][tmelem] = props[chave];
		}		
	}
	var propsCss = {"border":props.borderSize+"px solid "+props.borderColor,"backgroundColor":props.fillColor,"width":props.width,"height":props.height,"top":props.top,"left":props.left};
	var trinHTML = $('<div class="tmpelement eleTriangle">').css({"position":"absolute","z-index":10}).css(propsCss).attr("id","el_"+props.id);
	trinHTML.append('<img src="assets/triangulo_invertido.png">').find("img").css({"width":"100%","height":"100%"});
	return trinHTML;
};
EditorReport.prototype.addImage = function(props){
	if(!props.id){
		var tmelem = _jeport.images.id.length;
		props.id = "im_"+props.band+"_"+tmelem;
		for(var chave in props){	
			_jeport.images[chave][tmelem] = props[chave];
		}		
	}
	var propsCss = {"border":props.borderSize+"px solid "+props.borderColor,"backgroundColor":props.fillColor,"width":props.width,"height":props.height,"top":props.top,"left":props.left};
	var trinHTML = $('<div class="tmpelement eleImage">').css({"position":"absolute","z-index":10}).css(propsCss).attr("id","el_"+props.id);
	trinHTML.append('<img src="'+props.imgSrc+'">').find("img").css({"width":"100%","height":"100%"});
	
	return trinHTML;
};
EditorReport.prototype.addTriangle_ = function(props){
	if(!props.id){
		var tmelem = _jeport.visual_elements.id.length;
		props.id = "ve_"+props.band+"_"+tmelem;
		for(var chave in props){	
			_jeport.visual_elements[chave][tmelem] = props[chave];
		}		
	}	
	var propsCss = {"border":props.width/4+"px solid transparent","width":props.width,"height":props.height,"top":props._top,"left":props._left};
	propsCss.width = 0;
	propsCss.height = 0;
	propsCss["border-bottom-color"] = props.fillColor;	
	return $('<div class="tmpelement eleTriangle">').css({"position":"absolute","z-index":10}).css(propsCss).attr("id","el_"+props.id);
};
EditorReport.prototype.addTextElement = function(props){					
	var propsCss = {"fontSize":props.fontSize+"px","color":props.fontColor};
	return $('<label>'+props.text+'</label>').css(propsCss);
};
EditorReport.prototype.addTextField = function(props){
	props = $.extend({"_top":0,"type":"textField","textHorizontalAlign":"left","textVerticalAlign":"left","fillColor":"#000000","fontSize":12,"fontColor":"#000000","width":0,"height":0,"top":0,"left":0,"text":""},props);
	var htmlText = this.addElement(props);					
	htmlText.append(this.addTextElement(props));
	htmlText.addClass("eleTextField");
	return htmlText;
};
EditorReport.prototype.addText = function(props){
	props = $.extend({"_top":0,"type":"text","textHorizontalAlign":"left","textVerticalAlign":"left","fillColor":"#000000","fontSize":12,"fontColor":"#000000","width":0,"height":0,"top":0,"left":0,"text":""},props);
	var htmlText = this.addElement(props);					
	htmlText.append(this.addTextElement(props));
	htmlText.addClass("eleText");
	return htmlText;
};
EditorReport.prototype.addBand = function (p_dtareport,p_band_index){
	var paiBand = $("#designboard .designpager");				
	p_dtareport.bands["_top"][p_band_index] = 0;	
	var heightAnterior = 0;	
	if(p_band_index > 0){
		p_dtareport.bands["_top"][p_band_index] = p_dtareport.bands["_top"][p_band_index-1]+ p_dtareport.bands["height"][p_band_index-1];
		//paiBand.offset().top
	}else{
		p_dtareport.bands["_top"][p_band_index] = parseInt(paiBand.offset().top)
	}				
	var bandHTML = $("<div>").attr("id","el_"+p_dtareport.bands["band"][p_band_index]).addClass("designpagerband").addClass(p_dtareport.bands["band"][p_band_index]).css({"position":"relative","height":p_dtareport.bands["height"][p_band_index]+"px"});
	paiBand.append(bandHTML);
	return null;
};
EditorReport.prototype.addElements = function (p_dtareport_elements){	
	var tmList = p_dtareport_elements.type.length;	
	for(var e = 0;e<tmList;e++){
		var tmpElement = {};
		for(var chave in p_dtareport_elements){	
			tmpElement[chave] = p_dtareport_elements[chave][e];
		}	
		var bandHTML =$("#designpagerele .designpagerband:eq("+tmpElement.band+")");
		if(tmpElement.type=="text"){
			bandHTML.append(this.addText(tmpElement));
		}else if(tmpElement.type=="textField"){
			bandHTML.append(this.addTextField(tmpElement));
		}else if(tmpElement.type=="triangle"){			
			bandHTML.append(this.addTriangle(tmpElement));
		}else if(tmpElement.type=="rect"||tmpElement.type=="square"){
			bandHTML.append(this.addRect(tmpElement));
		}else if(tmpElement.type=="image"){			
			bandHTML.append(this.addImage(tmpElement));
		}	
	}
	return null;
};
EditorReport.prototype.addTreeViewItem = function (tmpitem){	
	var txtdesc = tmpitem["id"];
	var visualClass = "textelement";
	var visualIconClass = "usd";
	if(tmpitem["type"]=="textField"){
		txtdesc = tmpitem["text"];
		visualClass = "fieldtextelement";								
	}else if(tmpitem["type"]=="text"){
		txtdesc = tmpitem["text"];
		visualIconClass = "font";
	}else if(tmpitem["type"]=="rect"||tmpitem["type"]=="square"){
		visualIconClass = "unchecked";
	}else if(tmpitem["type"]=="image"){	
		visualIconClass = "picture";
	}else if(tmpitem["type"]=="triangle"){	
		visualIconClass = "play";
	}		
	var bandHTML =$("#subconteudo .treeview ul.band:eq("+tmpitem.band+")");
	var htmlTreeBandItem = $('<li id="tree_item_id_el_'+tmpitem["id"]+'"><span class="glyphicon glyphicon-'+visualIconClass+'"></span> '+txtdesc+' <span class="remove_item glyphicon glyphicon-remove"></span></li>');
	htmlTreeBandItem.addClass(visualClass);	
	bandHTML.append(htmlTreeBandItem);
	return null;
}	
EditorReport.prototype.addTreeViewItems = function (p_dtareport_elements){
	
	var tmList = p_dtareport_elements.type.length;	
	for(var e = 0;e<tmList;e++){
		var tmpitem = {};
		tmpitem["type"] = p_dtareport_elements["type"][e];
		tmpitem["id"] = p_dtareport_elements["id"][e];
		tmpitem["band"] = p_dtareport_elements["band"][e];
		if(tmpitem["type"]=="text"||tmpitem["type"]=="textField"){
			tmpitem["text"] = p_dtareport_elements["text"][e];
		}
		
		this.addTreeViewItem(tmpitem);
	}
	return null;
}			
EditorReport.prototype.createTreeView = function (p_dtareport){
	//var bandS = p_dtareport.bands[p_band_index];
	var htmlTree = $('<ul><span class="glyphicon glyphicon-file"></span>'+p_dtareport.reportName+'</ul>');
	htmlTree.addClass("treeview");

	htmlTreeItem = $('<ul><span class="glyphicon glyphicon-hdd"></span>'+p_dtareport.dataSets[0].dataSet+'</ul>');
	htmlTreeItem.addClass("dataset");
	
	var dtasets = p_dtareport.dataSets[0].itens;
	var tmdtasets = dtasets.length;
	if(tmdtasets > 0){
		for(var attrt in dtasets[0]){
			var htmlTreeDta = $("<li>"+attrt+"</li>");
			htmlTreeDta.addClass("item");
			htmlTreeItem.append(htmlTreeDta);	
		}
	}
	htmlTree.append(htmlTreeItem);
	var variablest = {
									"pageCount":0
									,"pageSum":0
									,"dateTime":0
									,"date":0
									,"rowCount":0
									,"rowSum":0
								};
	htmlTreeItem = $('<ul><span class="glyphicon glyphicon-tags"></span>variables</ul>');
	htmlTreeItem.addClass("dataset");
	for(var attrt in variablest){
			var htmlTreeDta = $("<li>"+attrt+"</li>");
			htmlTreeDta.addClass("item variableitem");
			htmlTreeItem.append(htmlTreeDta);	
		}
	
	htmlTree.append(htmlTreeItem);
		
	for(var i = 0;i<5;i++){
		var bandS = p_dtareport.bands["band"][i];
		var htmlTreeBand = $('<ul><span class="glyphicon glyphicon-tag"></span>'+bandS+'</ul>');
		htmlTreeBand.addClass("band "+"b_"+bandS).attr("id","b_el_"+bandS);	
		htmlTree.append(htmlTreeBand);
	}
	
	$('#subconteudo').find("ul.treeview:first").remove().end().append(htmlTree);	
	
	this.addTreeViewItems(p_dtareport.visual_elements);
	this.addTreeViewItems(p_dtareport.images);
	this.addTreeViewItems(p_dtareport.texts);	
	
	this.setReportTreeViewEvents();
	return null;
};
EditorReport.prototype.setSource = function(){
	$('#sourceboard textarea').val(JSON.stringify(_jeport));
};

EditorReport.prototype.saveReport = function(){
	//var vlCookete =  $('#sourceboard textarea').val().replace(/\n|\t/gm,"").replace(/"/gm,"'");
	//vlCookete = $.trim(vlCookete);
	var valorO = $.parseJSON($('#sourceboard textarea').val());	
	var exdays = 60;
	var cname = "reporttmp2";
	var cvalue = JSON.stringify(valorO);
	cvalue = this.applyDictionary(cvalue);
    var d = new Date();
    d.setTime(d.getTime() + (exdays*24*60*60*1000));
    var expires = "expires=" + d.toGMTString();
    document.cookie = cname+"="+cvalue+"; "+expires;
	
};

EditorReport.prototype.loadReport = function(){
	//editorR.clearReport();
	var result = document.cookie.match(new RegExp('reporttmp2' + '=([^;]+)'));
	//result && (result = JSON.parse(result[1]));
	
	_jeport = {};
	var tmprs = "";
	if(result && 1 > 9){
		tmprs = result[1];
		tmprs = this.removeDictionary(tmprs);
	}else{
		tmprs = $('#sourceboard textarea').val();	
	}	
	//tmprs = $('#sourceboard textarea').val();
	//alert(tmprs);		
	_jeport = $.parseJSON(tmprs);
	editorR.setReport(_jeport);		
	editorR.createTreeView(_jeport);
	editorR.clearReport();
};
EditorReport.prototype.applyDictionary = function(vlw){
	var dicts1 = [
	'type','textField','textExpression','text','rect','triangle','image',
	'width','height','top','left','id','borderSize','borderColor','fillColor',
	'textHorizontalAlign','textVerticalAlign','fontSize','fontColor',
	'bands','band','elements','itens','reportName','orientaction','dataSets','version',
	'portrait','center'
	];
	var tmLd = dicts1.length;
	for(var i =0;i<tmLd;i++){		
		vlw = vlw.replace(new RegExp('"'+dicts1[i]+'"',"gm"),"'_"+i+"'");
	}	
	return vlw.replace(/"/gm,"'");
};
EditorReport.prototype.removeDictionary = function(vlw){
	var dicts1 = [
	'type','textField','textExpression','text','rect','triangle','image',
	'width','height','top','left','id','borderSize','borderColor','fillColor',
	'textHorizontalAlign','textVerticalAlign','fontSize','fontColor',
	'bands','band','elements','itens','reportName','orientaction','dataSets','version',
	'portrait','center'
	];
	var tmLd = dicts1.length;
	for(var i =0;i<tmLd;i++){		
		vlw = vlw.replace(new RegExp("'_"+i+"'","gm"),"'"+dicts1[i]+"'");
	}	
	return vlw.replace(/'/gm,'"');
};
EditorReport.prototype.json2db = function(jsonArrayObject){
/*
{
 "nome":["maria","julia","marcos"]
,"pac" :[123155 ,454544 ,5445445 ]
}
*/
	var headerArrayObject = {};
	var tml = jsonArrayObject.length;
	if(tml>0){
		for(var chave in jsonArrayObject[0]){			
			headerArrayObject[chave] = [];
			for(var y = 0;y < tml;y++){
				headerArrayObject[chave][y] = jsonArrayObject[y][chave];
			}
		}
		
	}
	return headerArrayObject;
};

EditorReport.prototype.clearReport = function(){
	var domainname = window.location.host.toString();
	//var domainname = "www.cavalodoido.com.br";
	document.cookie = ['reporttmp2', '=; expires=Thu, 01-Jan-1970 00:00:01 GMT; path=/; domain=.',domainname].join('');
};
